package com.ny.teatreport6;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

class Employee implements Serializable {
    private String name;
    private int age;
    private double salary;

    public Employee(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public double getSalary() {
        return salary;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                '}';
    }
}

public class Test {
    public static void main(String[] args) {

        Employee emp1 = new Employee("张三", 28, 8500.0);
        Employee emp2 = new Employee("李四", 35, 12000.0);
        Employee emp3 = new Employee("王五", 42, 15000.0);

        List<Employee> employees = new ArrayList<>();
        employees.add(emp1);
        employees.add(emp2);
        employees.add(emp3);

        String filePath = "employees.dat";

        try {
            writeEmployeesToFile(employees, filePath);

            List<Employee> loadedEmployees = readEmployeesFromFile(filePath);
            System.out.println("从文件中读取的员工信息:");
            for (Employee emp : loadedEmployees) {
                System.out.println(emp);
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static void writeEmployeesToFile(List<Employee> employees, String filePath) throws IOException {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath))) {
            oos.writeObject(employees);
            System.out.println("员工信息已成功写入文件: " + filePath);
        }
    }


    private static List<Employee> readEmployeesFromFile(String filePath)
            throws IOException, ClassNotFoundException {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath))) {
            @SuppressWarnings("unchecked")
            List<Employee> employees = (List<Employee>) ois.readObject();
            return employees;
        }
    }
}
